<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\db;
use think\config;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    
                    //公司客服数量加一
                    $this->companyKfCountInc($params);
                    //添加客服前端样式
//                    $companyId = $this->model->getLastInsID();
//                    $this->addChatStyle($companyId);
                    

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->getCompanyAssign();
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    //新公司客服数量加一
                    $this->companyKfCountInc($params);
                    //旧公司客服数量减一
                    $this->companyKfCountDec($params['old_company_id']);
                    unset($params['old_company_id']);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->getCompanyAssign();
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);

        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);

        //旧公司客服数量减一
        $this->companyKfCountDec($row['company_id']);

        $this->success();
    }

    /**
     * 获取公司列表，并赋值给模板
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    private function getCompanyAssign(){
        $companyList = collection(model('Company')->where(['status'=>1])->select())->toArray();
        $this->assign('companyList', $companyList);
    }

    /**
     * 公司客服数量加一
     * @param $params
     * @throws \think\Exception
     */
    private function companyKfCountInc($params){
        $company_id = $params['company_id'];
        if(!empty($company_id)){
            $companyModel = model("Company");
            $companyInfo = $companyModel->field('id,kf_count,status')->where(['id'=>$company_id])->find();
            if(empty($companyInfo['id']) || $companyInfo['status'] != 1){
                $this->error(__('公司信息不合法！', ''));
            }
            $companyModel->where(['id'=>$company_id])->setInc('kf_count');
        }
    }

    /**
     * 公司客服数量减一
     * @param $params
     * @throws \think\Exception
     */
    private function companyKfCountDec($companyId){
        if(!empty($companyId)){
            $companyModel = model("Company");
            $companyInfo = $companyModel->field('id,kf_count,status')->where(['id'=>$companyId])->find();
            if(empty($companyInfo['id']) || $companyInfo['status'] != 1){
                $this->error(__('公司信息不合法！', ''));
            }
            $companyModel->where(['id'=>$companyId])->setDec('kf_count');
        }
    }
    
    /**
     * 添加默认前端聊天样式
     */
    private function addChatStyle($companyId){
        $parm = [
            'cid'=>$companyId,
            'color' =>Config::get('chatstyle.default_style_color'),
            'message_display' =>Config::get('chatstyle.default_message_display'),
            'message_title' =>Config::get('chatstyle.default_message_title'),
            'm_popup_display' =>Config::get('chatstyle.default_m_popup_display'),
            'm_popup_title1' =>Config::get('chatstyle.default_m_popup_title1'),
            'm_popup_title2' =>Config::get('chatstyle.default_m_popup_title2'),
            'm_popup_img' =>Config::get('chatstyle.default_m_popup_img'),
            'r_popup_display' =>Config::get('chatstyle.default_r_popup_display'),
            'r_popup_title1' =>Config::get('chatstyle.default_r_popup_title1'),
            'r_popup_title2' =>Config::get('chatstyle.default_r_popup_title2'),
        ];
        
        model("Chatstyle")->save($parm);
    }

}
